﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BlogEngine.Core.Web.Controls
{
	public class PostListBase : UserControl
	{
		private int _page;
		
		protected void Page_Init(object sender, EventArgs e)
		{
			string qpage = Request.QueryString["page"];

			if (!Int32.TryParse(qpage, out _page))
				_page = 1;

			_page = Math.Max(_page, 1);

			int count = BlogSettings.Instance.PostsPerPage;
			int index = (_page - 1) * count;
			
			switch (Request.QueryString["type"])
			{
				case "author":
					if (!String.IsNullOrEmpty(Request.QueryString["name"]))
					{
						Posts = Post.GetPostsByAuthor(Request.QueryString["name"]); ;
						Page.Title = BlogSettings.Instance.Name + " - All posts by " + Request.QueryString["name"];
					}
					break;

				case "category":
					if (!String.IsNullOrEmpty(Request.QueryString["slug"]))
					{
						Posts = Post.GetPostsByTerm(TermType.Category, Request.QueryString["slug"]); ;
						Page.Title = BlogSettings.Instance.Name + " - All posts in " + Request.QueryString["slug"]; ;
					}
					break;

				case "tag":
					if (!String.IsNullOrEmpty(Request.QueryString["slug"]))
					{
						Posts = Post.GetPostsByTerm(TermType.Tag, Request.QueryString["slug"]); ;
						Page.Title = BlogSettings.Instance.Name + " - All posts in " + Request.QueryString["slug"]; ;
					}
					break;

				default:
					if (Request.QueryString["year"] != null || Request.QueryString["date"] != null || Request.QueryString["calendar"] != null)
					{
						DisplayDateRange(index, count);
					}
					else if (Request.QueryString.Count == 0 || !String.IsNullOrEmpty(Request.QueryString["page"]) || !String.IsNullOrEmpty(Request.QueryString["theme"]) || !String.IsNullOrEmpty(Request.QueryString["blog"]))
					{
						Posts = Post.GetPosts(index, count);
						Page.Title = BlogSettings.Instance.Name + " - " + BlogSettings.Instance.Description;
					}
					break;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (Page.IsCallback)
				return;

			DataBind();
		}

		/// <summary>
		/// Binds the list of posts to individual postview.ascx controls
		/// from the current theme. 
		/// </summary>
		public override void DataBind()
		{
			string theme = BlogSettings.Instance.Theme;
			if (Request.QueryString["theme"] != null)
				theme = Request.QueryString["theme"];

			string path = Utils.RelativeWebRoot + "themes/" + theme + "/PostView.ascx";
			Control posts = FindControl("PostsList");

			foreach (Post post in Posts)
			{
				if (post.IsVisible || Page.User.Identity.IsAuthenticated)
				{
					PostViewBase postView = (PostViewBase)LoadControl(path);
					postView.ShowExcerpt = BlogSettings.Instance.ShowDescriptionInPostList;
					postView.Post = post;
					postView.Location = ServingLocation.PostList;

					posts.Controls.Add(postView);
				}
			}

			InitPaging();
		}

		#region Properties

		/// <summary>
		/// The list of posts to display.
		/// </summary>
		public List<Post> Posts
		{
			get { return (List<Post>)(ViewState["Posts"] ?? default(List<Post>)); }
			set { ViewState["Posts"] = value; }
		}

		#endregion

		private void DisplayDateRange(int index, int count)
		{
			string year = Request.QueryString["year"];
			string month = Request.QueryString["month"];
			string specificDate = Request.QueryString["date"];

			if (!String.IsNullOrEmpty(year) && !String.IsNullOrEmpty(month))
			{
				DateTime dateFrom = DateTime.Parse(year.Substring(0, 4) + "-" + month + "-01", CultureInfo.InvariantCulture);
				DateTime dateTo = dateFrom.AddMonths(1).AddMilliseconds(-1);
				Posts = Post.GetPostsByDate(dateFrom, dateTo, index, count);
				Page.Title = BlogSettings.Instance.Name + " - " + dateFrom.ToString("MMMM yyyy");
			}
			else if (!String.IsNullOrEmpty(specificDate) && specificDate.Length == 10)
			{
				DateTime date = DateTime.Parse(specificDate, CultureInfo.InvariantCulture);
				Posts = Post.GetPostsByDate(date, date, index, count);
				Page.Title = BlogSettings.Instance.Name + " - " + date.ToString("MMMM d. yyyy");
			}
			else if (!String.IsNullOrEmpty(Request.QueryString["calendar"]))
			{
				// TODO: put calendar in here
			}
		}

		/// <summary>
		/// Initializes the Next and Previous links
		/// </summary>
		private void InitPaging()
		{
			string path = Request.RawUrl.Replace("Default.aspx", String.Empty);

			if (path.Contains("?"))
			{
				if (path.Contains("page="))
				{
					int index = path.IndexOf("page=");
					path = path.Substring(0, index);
				}
				else
				{
					path += "&";
				}
			}
			else
			{
				path += "?";
			}

			string url = path + "page={0}";

			HyperLink next = (HyperLink)FindControl("ForwardLink");
			HyperLink back = (HyperLink)FindControl("BackwardLink");

			next.NavigateUrl = String.Format(url, _page + 1);
			back.NavigateUrl = String.Format(url, _page - 1);

			next.Visible = _page < Post.Count / BlogSettings.Instance.PostsPerPage;
			if (next.Visible)
				(Page as BlogBasePage).AddGenericLink("next", "Next page", next.NavigateUrl);

			back.Visible = _page > 1;
			if (back.Visible)
				(Page as BlogBasePage).AddGenericLink("prev", "Previous page", back.NavigateUrl);
		}
	}
}
